package com.edu.utils;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @Author ZCN
 * @Date 2021/11/14 0:21
 * @Version 1.0
 **/
public class DBCPUtil {
    private static Properties properties = new Properties();
    private static BasicDataSource dataSource = new BasicDataSource();

    //加载DBCP配置文件
    static {
        try {
            InputStream is = new DBCPUtil().getClass().getClassLoader().getResourceAsStream("dbConfig.properties");
            properties.load(is);
            dataSource = BasicDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //从连接池中获取一个连接
    public static Connection getConnection() {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
}

